<template>
  <div class="page">
    <h4 style="margin-left: 12px;">HIS账号管理</h4>
    <el-row :gutter="20">
      <el-form ref="formInline" :inline="true" :model="formInline" id="formbox">
        <el-form-item label="机构：" prop="institution" class="mag">
          <el-select
            v-model="formInline.institution"
            placeholder="请选择机构"
            @change="handleChange"
          >
            <el-option
              v-for="option in InstitutionList"
              :key="option"
              :label="option"
              :value="option"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科室：" prop="department" class="mag">
          <el-select v-model="formInline.department" placeholder="请选择科室">
            <el-option
              v-for="option in DepartmentList"
              :key="option"
              :label="option"
              :value="option"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户：" prop="hisUserName" class="mag">
          <!-- <el-select v-model="formInline.hisUserName" placeholder="请选择用户">
                <el-option
                  v-for="option in user"
                  :key="option.id"
                  :label="option.hisUserName"
                  :value="option.hisUserName"
                >
                </el-option>
              </el-select> -->
          <el-input
            v-model="formInline.hisUserName"
            placeholder="请输入用户名称"
            @input="getUsers()"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="创建时间 ：" prop="createTime">
          <el-date-picker
            v-model="formInline.createTime"
            :disabled-date="disableFutureDates"
            type="daterange"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            range-separator="-"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            size="large"
          />
        </el-form-item>

        <el-col :span="4">
          <el-form-item class="poin">
            <el-button type="primary" @click="searchSubmit()">查询</el-button>
            <el-button @click="onReset('formInline')">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <el-row class="op">
      <el-col :span="12"
        ><h4>用户列表 (共{{ total }}条)</h4></el-col
      >
      <el-col :span="12" class="tr">
        <el-button type="primary" @click="dialogUploadVisible = true"
          >导入HIS用户</el-button
        >
        <el-button type="success" @click="downloadTemp()"
          >下载导入模板</el-button
        >
        <el-button type="primary" @click="addUsers()">新增</el-button>
      </el-col>
    </el-row>
    <!-- <el-empty
          v-if="total==0"
          :image-size="200"
          description="暂无记录"
        ></el-empty> -->
    <el-row>
      <el-table
        ref="multipleTable"
        border
        :data="renderData"
        style="width: 100%"
         max-height="470px"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />

        <el-table-column
          prop="institution"
          label="机构"
          align="center"
          width="200"
        ></el-table-column>
        <el-table-column
          prop="department"
          label="科室"
          align="center"
          width="200"
        ></el-table-column>
        <el-table-column
          prop="hisUserName"
          label="用户"
           width="200"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="userName"
          label="已绑定账号"
          align="center"
          width="200"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="200"
          align="center"
        ></el-table-column>
        <el-table-column prop="remark" label="备注"  width="150" align="center">
        </el-table-column>
        <el-table-column label="操作" width="280" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)"
              >编辑</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)"
              >修改His密码</el-button
            >
            <el-button
              v-show="scope.row.isBound!==1"
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-col :span="24" style="display: flex; justify-content: end;margin-bottom: 50px;">
      <el-pagination
        v-model:currentPage="this.page"
        v-model:page-size="this.size"
        :total="this.total"
        :page-sizes="[10, 20, 50, 100, 500]"
        class="new-pagination"
        small
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </el-col>
    <el-dialog :title="dialogType" v-model="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="机构" :label-width="formLabelWidth">
          <template #label> <span style="color: red">*</span>机构</template>
          <el-input
            v-model="form.institution"
            autocomplete="off"
            placeholder="请输入机构"
          ></el-input>
        </el-form-item>
        <el-form-item label="科室" :label-width="formLabelWidth">
          <template #label> <span style="color: red">*</span>科室</template>
          <el-input
            v-model="form.department"
            autocomplete="off"
            placeholder="请输入科室"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户" :label-width="formLabelWidth">
          <template #label> <span style="color: red">*</span>用户</template>
          <el-input
            v-model="form.hisUserName"
            autocomplete="off"
            placeholder="请输入用户"
          ></el-input>
        </el-form-item>
        <el-form-item label="新密码" :label-width="formLabelWidth">
          <template #label> <span style="color: red">*</span>密码</template>
          <el-input
            v-model="form.password"
            autocomplete="off"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
            v-model="form.remark"
            autocomplete="off"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog_footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dialogType" v-model="PasswordChangeFormVisible">
      <el-form :model="PasswordChangeForm">
        <el-form-item label="新密码" :label-width="formLabelWidth">
          <template #label> <span style="color: red">*</span>密码</template>
          <el-input
            v-model="PasswordChangeForm.lodPassword"
            autocomplete="off"
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth">
          <template #label> <span style="color: red">*</span>确认密码</template>
          <el-input
            v-model="PasswordChangeForm.newPassword"
            autocomplete="off"
            placeholder="请再次输入密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog_footer">
        <el-button @click="PasswordChangeFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handPassword()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dialogType" v-model="dleIdFormVisible">
      <div>
        <i
          class="el-icon-warning"
          style="font-size: 40px; color: #e6a23c; margin: 0 20px"
        ></i>
        <span>确定删除用户： {{ dleId }}</span>
      </div>

      <div slot="footer" class="dialog_footer">
        <el-button @click="dleIdFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dleUser()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="导入HIS用户" v-model="dialogUploadVisible">
      <el-upload
        ref="upload"
        class="upload-demo"
        :action="url"
        :limit="1"
        :before-upload="beforeUpload"
        :on-change="handleUploadChange"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-success="uploadSuccess"
        :on-error="handleError"
        :file-list="fileList"
        :auto-upload="false"
      >
        <el-button slot="trigger" size="small" type="primary"
          >选取文件</el-button
        >
        <el-button
          style="margin-left: 10px"
          size="small"
          type="success"
          @click="submitUpload"
          >上传</el-button
        >
        <div slot="tip" class="el-upload__tip">
          只能上传XLSX/CSV文件，且不超过500M
        </div>
      </el-upload>
    </el-dialog>
    <el-dialog :title="dialogType" v-model="openVisible">
      <el-form :model="openform" :rules="rules" ref="openForm">
        <el-form-item label="密码" :label-width="formLabelWidth"  v-show="dialogType == '新增' ? true : false">
          <template #label> <span style="color: red">*</span>密码</template>
          <el-input
            v-model="openform.password"
            autocomplete="off"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="机构" :label-width="formLabelWidth" class="Deparsele">
          <template #label> <span style="color: red">*</span>机构</template>
          <el-select
            v-model="openform.institution"
            placeholder="请选择机构"
            @change="handleChange"
            :disabled="dialogType == '编辑' ? true : false"
          >
            <el-option
              v-for="option in InstitutionList"
              :label="option"
              :value="option"
              :key="option"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="科室" :label-width="formLabelWidth"  >
          <template #label> <span style="color: red">*</span>科室</template>
          <!-- @change="handleChange2" -->
          <el-select  ref="Depar" v-model="openform.department" placeholder="请选择科室"  :disabled="dialogType == '编辑' ? true : false" class="Deparsele">
            <el-option
              v-for="option1 in DepartmentList"
              :label="option1"
              :value="option1"
              :key="option1"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户" :label-width="formLabelWidth">
          <template #label> <span style="color: red">*</span>用户</template>
          <el-input
            v-model="openform.hisUserName"
            autocomplete="off"
            placeholder="请输入用户"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
            v-model="openform.remark"
            autocomplete="off"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
        <div class="tip" v-show="dialogType == '新增'">
          <span>注:无未绑定的HIS用户时，请在HIS账号管理中新增</span>
        </div>
      </el-form>
      <div slot="footer" class="dialog_footer">
        <el-button @click="handerOFF">取 消</el-button>
        <el-button type="primary" @click="Submit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { baseURL } from "../utils/utils";
import http from "@/utils/request";
import { ElMessage } from "element-plus";
const disableFutureDates = (time) =>  time > new Date();
export default {
  name: "UsersPage",
  data() {
    const validture = (rule, value, callback) => {
      if (value !== "") {
        callback();
      } else {
        callback(new Error("此项为必填"));
      }
    };
    return {
      url: "/hisInfo/template",
      dialogFormVisible: false,
      PasswordChangeFormVisible: false,
      dleIdFormVisible: false,
      dialogUploadVisible: false,
      openVisible: false,

      formInline: {
        // 角色
        roleName: "",
        userName: "",
        createTime: "",
        startTime: "",
        endTime: "",
        // 机构
        institution: "",
        // 科室
        department: "",
        // 绑定HIS账号id
        hisAccountId: "",
        hisUserName: "",
        remark: "",
      },
      dialogType: "新增",
      people: null,
      formLabelWidth: "120px",
      form: {
        hisUserName: "",
        password: "",
        institution: "",
        department: "",
        remark: "",
      },
      openform: {
        id: "",
        // 角色
        userName: "",
        password: "",
        createTime: "",
        endTime: "",
        // 机构
        institution: "",
        // 科室
        department: "",
        // 绑定HIS账号id
        hisAccountId: "",
        remark: "",
        hisUserName: "",
     },
     rules: {
        // role: [{ required: true, validator: validture, trigger: "blur" }],
        userName: [{ required: true, validator: validture, trigger: "blur" }],
        // password: [{ required: true, validator: validture, trigger: "blur" }],
        // 机构
        institution: [
          { required: true, validator: validture, trigger: "blur" },
        ],
        // 科室
        department: [{ required: true, validator: validture, trigger: "blur" }],
        // 绑定HIS账号id
        hisUserName: [
          { required: true, validator: validture, trigger: "blur" },
        ],
      },
      // 修改密码数据
      PasswordChangeForm: {
        id: "",
        lodPassword: "",
        newPassword: "",
        hisUserName: "",
      },
      // 要删除id
      dleId: "",
      // 导入数组
      fileList: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e7;
        },
      },
      tableData: [],
      renderData: [],
      page: 1,
      size: 10,
      total: 0,
      DepartmentList: [],
      InstitutionList: [],
      user: [],
      uid: "",
    };
  },
  mounted() {
    this.getUsers();
    this.getHislist();
    this.getInstitutionList();
    // this.getDepartmentList();
  },
  methods: {
    disableFutureDates,
    handerOFF(){
     this.openVisible = false; 
    },
    Submit(){
      this.$refs.openForm.validate((valid) => {
        if (valid) {
          http
            .post("/hisInfo/updateHisInfo", {
              id:this.openform.id,
              hisUserName:this.openform.hisUserName,
              remark:this.openform.remark,
            }).then((res) => {
              if(res.code==0){
                ElMessage.success(res.msg);
                this.openVisible = false;
                this.getUsers();
                this.getInstitutionList()
              }else{
              
              }
            })
            .catch((err) => {
            
            });
        }
      });
    },
    handleChange(value) {
      this.jg = value;
      this.formInline.department = "";
      http
        .post(
          "/admin/sysUser/getDepartmentList",
        {
            institution: value,
          }
        )
        .then((res) => {
          this.DepartmentList = res.data;
        });
    },
    handleUploadChange(file) {
      // const config = {
      //   headers: {
      //     "Content-Type": "multipart/form-data",
      //   },
      // };
      // let formDate = new FormData();
      // formDate.append("file", file);
      //http.post("/user/import",formDate,config)
    },
    beforeUpload(file) {
      let formDate = new FormData();
      formDate.append("file", file);
      return formDate;
    },
    getHislist() {
      http
        .post("/admin/sysUser/getHisUserList", {
          hisUserName: this.formInline.hisUserName,
        })
        .then((res) => {
          if(res.code=200){
            this.user = res.data;
          }
         
        });
    },
    getInstitutionList() {
      http.post("/admin/sysUser/getInstitutionList").then((res) => {
        this.InstitutionList = res.data;
      });
    },
    getDepartmentList() {
      http.post("/admin/sysUser/getDepartmentList").then((res) => {
        this.DepartmentList = res.data;
      });
    },
    onBack() {
      window.location.href = "/";
    },
    downloadTemp() {
      http.post("/hisInfo/template").then((res) => {
        // console.log(res.data);
        window.open(res.data);
      });
    },
    onSubmit() {
      const { hisUserName, password, institution, department, remark } =
        this.form;
      if (!hisUserName || !password || !institution || !department) {
        return ElMessage.error("请完整填写表单");
      }
    
        http
        .post("/hisInfo/addHisUser", {
          hisUserName,
          password,
          institution,
          department,
          remark,
        })
        .then((res) => {
          if (res.code==200) {
            ElMessage.success(res.message);
            this.getUsers();
            this.getInstitutionList();
          }
          this.dialogFormVisible = false;
        });
  
     
    },
    searchSubmit() {
      this.getUsers();
    },
    getUsers() {
      const requestData = { page: this.page, size: this.size };
      for (const key in this.formInline) {
        if (this.formInline[key]) {
          requestData[key] = this.formInline[key];
          if(key=='createTime'){
          this.formInline.endTime=this.formInline.createTime[1];
          this.formInline.startTime=this.formInline.createTime[0];    
          }
        }
      }
      delete requestData.createTime;
      http.post("/hisInfo/getPageList", requestData).then((res) => {
        if(res.code=200){
          this.renderData = res.data.list;
          this.total = res.data.total;
        }
       
      });
    },
    onReset(formName) {
      this.$refs[formName].resetFields();
      this.DepartmentList = [];
      this.formInline.endTime="";
        this.formInline.startTime=""; 
    },
    handleSizeChange(val) {
      this.size = val;
      this.page = 1;
      this.getUsers();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getUsers();
      // console.log(`当前页: ${val}`);
    },
    addUsers() {
      this.form = {
        hisUserName: "",
        password: "",
        institution: "",
        department: "",
        remark: "",
      };
      this.dialogType = "新增";
      this.dialogFormVisible = true;
    },
    //编辑
    handleView(row){
      this.openVisible=true;
      this.dialogType="编辑";
      this.openform={...row}
    },
    // 修改密码弹窗
    handleEdit(row) {
      console.log(row);
      (this.PasswordChangeForm = {
        id: row.id,
        lodPassword: "",
        newPassword: "",
        hisUserName: row.hisUserName,
      }),
        (this.dialogType = "修改HIS密码");
      this.PasswordChangeFormVisible = true;
    },
    // 删除弹窗
    handleDelete({ hisUserName, id ,roleName,hisAccountId}) {
      this.$confirm(`是否删除该用户: ${hisUserName}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (roleName == '管理员') {
            ElMessage.error("管理员不能删除");
          } else {
            const requestData = { id: id, hisAccountId: hisAccountId };
            http
              .post("/hisInfo/deleteHisUser", {
                id,
              })
              .then((res) => {
                if(res.code==200){
                  ElMessage.success(res.message);
                  this.getUsers();
                }
               
                this.dleIdFormVisible = false;
                
              });
          }
        })
       
    },
    dleUser() {
      http
        .post("/user/deleteHisUser", {
          id: this.uid,
        })
        .then((res) => {
          if(res.code==200){
            ElMessage.success(res.message);
            this.getUsers();
          }
          this.dleIdFormVisible = false;
       
        });
    },
    goto(url) {
      window.location.href = url;
    },
    // getNewDate(newV) {
    //   if (this.tableData.length > 0) {
    //     const v = newV;
    //     const newDate = this.tableData.slice(
    //       (v - 1) * this.page_size,
    //       v * this.page_size
    //     );
    //     this.renderData = newDate;
    //   }
    // },
    //修改密码
    handPassword() {
      const { id, lodPassword, newPassword, hisUserName } =
        this.PasswordChangeForm;
      if (!lodPassword && !newPassword) {
        return ElMessage.error("请完整填写表单");
      }
      if (lodPassword != newPassword) {
        return ElMessage.error("两次密码输入不一致");
      }
      http
        .post("/hisInfo/updatePassword", {
          // hisUserName,
          id,
          newPassword,
          resetPassword: lodPassword,
          // remark: newPassword,
        })
        .then((res) => {
          if(res.code==200){
            ElMessage.success(res.message);
            this.getUsers();
          }
          this.PasswordChangeFormVisible = false;
        });
    },
    //删除

    //
    submitUpload() {
      this.$refs.upload.submit();
    },
    uploadSuccess() {
      ElMessage.success("导入成功");
      this.dialogUploadVisible = false;
      this.getUsers();
    },
    handleError() {
      ElMessage.error("导入居民资料失败");
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    handlePreview(file) {
      // console.log(file);
    },
  },
  watch: {
    page: {
      immediate: true,
      handler: function (newV) {
        // this.getUsers();
      },
    },
    size: {
      handler: function () {
        // this.getUsers();
      },
    },
  },
};
</script>
<style scoped lang="scss">
.el-table th.is-center,
.el-table td.is-center {
  text-align: center !important;
}
.page {
  padding: 10px 20px;
  width: 100%;
  box-sizing: border-box;
}
#formbox {
  display: flex;
  flex-wrap: wrap;
  padding: 0 30px;
}
.dialog_footer {
  margin-top: 20px;
  display: flex;
  justify-content: end;
}
.add_dialog {
  :deep(.el-select .el-select__wrapper) {
    min-height: 32px;
    width: 100% !important;
  }
}
:deep(.el-input__wrapper) {
  width: 230px;
}
:deep(.el-form-item .el-select__wrapper) {
  min-height: 32px;
  width: 252px;
}
:deep(.el-range-editor--large.el-input__wrapper) {
  height: 32px;
  width: 252px;
}
.form-button {
  display: flex;
  justify-content: start;
}
.table-container {
  display: flex;
  flex-direction: column;
}
:deep(.Deparsele .el-select__wrapper ){
  width: 100% !important;
}
.table-btn {
  display: flex;
  height: 50px;
  align-items: center;
  justify-content: space-around;
}
.tr {
  text-align: right;
  height: 50px;
  line-height: 50px;
}
::v-deep .all-disabled .el-checkbox__input .el-checkbox__inner {
  display: none;
}

.new-pagination {
  margin: 30px 0 10px 0 !important;
}
.required:before {
  content: "*";
  color: red;
  margin-right: 5px;
}

.box {
  display: flex;
  margin-right: 30px;
}
h1 {
  font-size: 14px;
  text-align: left;
  padding: 0;
}
h2 {
  font-size: 18px;
}
h3 {
  margin: 0;
}

.main-top {
  height: 50px;
  text-align: right;
  border-bottom: 1px solid #f1f1f1;
}
.main-top .el-button {
  height: 50px;
  width: 120px;
  font-size: 20px;
}
.main-filter {
  padding: 0 20px;
  border-bottom: 1px solid #f1f1f1;
}
.op {
  padding: 20px;
}
.op h4 {
  margin: 0;
  padding: 0;
}
.tr {
  text-align: right;
}
.tb {
  padding: 0 20px;
  overflow-y: scroll;
}
.el-menu-item-group__title {
  display: none;
}
.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
}
.mag {
  margin-right: 60px !important;
}
.mag1 {
  margin-right: 72px !important;
}
.mag2 {
  margin-right: 162px !important;
}
.input_height {
  height: 70px !important;
}
.tip {
  color: red;
  font-size: 12px;
  margin-left: 90px;
}
.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  width: 70vw;
}
</style>
